import React from 'react';
import './App.css';
import { _pay, _ask_status } from './api';

function App() {
  const payNow = async () => {
    const { data } = await _pay();
    if (data.code) {
      window.open(data.result);
      askStatus(data.trade_no);
    }
  }

  //  使用轮询查询支付状态
  const askStatus = (trade_no: string) => {
    const timer = setInterval(async () => {
      const { data } = await _ask_status(trade_no);
      if (data.code) {
        if (data.trade_status === "TRADE_SUCCESS" || data.trade_status === "TRADE_FINISHED") {
          clearInterval(timer);
          alert(data.msg);
          // 跳转到支付成功页面
        }

      } else {
        clearInterval(timer);
      }
    }, 3000)
  }
  return (
    <div className="App">
      <button onClick={() => payNow()}>立即支付</button>
    </div>
  );
}

export default App;
